package C037;

import java.util.Stack;

/**
 * ClassName: C05
 * Package: C037
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/23 16:31
 * @Version 1.0
 * @Since 1.0
 */
public class C05 {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(5);
        TreeNode treeNode1 = new TreeNode(4);
        TreeNode treeNode2 = new TreeNode(6);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(7);
        TreeNode treeNode5 = new TreeNode(2147483647);
        treeNode.left = treeNode1;
        treeNode.right = treeNode2;
        treeNode2.left = treeNode3;
        treeNode2.right = treeNode4;
        System.out.println(isValidBST(treeNode));
        System.out.println(isValidBST2(treeNode));
    }

    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public static boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        return process(root);
    }

    // 重要的思路是找出左边的最小，最大，右子树的最小与最大
    static long min, max;

    public static boolean process(TreeNode root) {
        if (root == null) {
            max = Long.MIN_VALUE;
            min = Long.MAX_VALUE;
            return true;
        }
        boolean lflag = process(root.left);
        long lmax = max;
        long lmin = min;
        boolean rflag = process(root.right);
        long rmax = max;
        long rmin = min;
        max = Math.max(root.val, rmax);
        min = Math.min(root.val, lmin);
        return lflag && rflag && root.val > lmax && root.val < rmin;
    }


    // 中序遍历的实现
    public static boolean isValidBST2(TreeNode root) {

        if (root == null) {
            return true;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode pre = null;
        while (!stack.isEmpty() || cur != null) {
            if (cur != null) {
                stack.push(cur);
                cur = cur.left;
            } else {
                cur = stack.pop();
                if(pre != null && pre.val >= cur.val) {
                    return false;
                }
                pre = cur;
                cur = cur.right;
            }
        }
        return true;
    }

}
